# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import math
import random
from datetime import date, datetime
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import never_cache
from django.forms.models import model_to_dict
from future.builtins import str
from wenlincms.utils.views import render
from django.core import serializers
from wlapps.utils.base62 import wldecode
from wlmodels.codes.models import ELHGGoodsCode
from wlmodels.company.models import ELPost, ELManager, ELInv, ELCaseDetail, ELCasePunish, ELPerson, ELMortReg, \
    ELMortGua, \
    ELMortClaim, ELStockFrost, ELStockImpawn, ELNameHistory, ELGetiPerson, ELCredit
from wlmodels.companyplus.models import ELFinanceTax, ELFinanceIndex, ELHGEnt, ELHGEntDetail, ELHGEntGoods
from wlmodels.dataplus.models import ELPatentEnt, ELStatisticsCredit, ELCopyrightSoftware, ELCopyrightProduction, \
    ELTminfo
from wlviews.apis.apis import FBAPI, WmyAPI
from wlviews.apis.utils import news_filter
from wlviews.saas.fee import customer_verify_fee, noauth_redirct_iframe
from .tupu import tupu_create_echarts_xml, edge_distinct, gen_touzi_edgetext
from .powerModel import getJsonData, getJsonScore, add_power_score
from .power_demo import getJsonDetail


def get_index_from_data_engine(id):
    return int(random.uniform(0, 72))


class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        # if isinstance(obj, datetime.datetime):
        #     return int(mktime(obj.timetuple()))
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


@never_cache
def company_report_for_java(request, entid):
    raw_entid = entid
    entid = wldecode(entid, addcrc=True)
    if not entid or entid > 500000000:
        raise Http404
    el_posts = ELPost.objects.all()
    el_post = get_object_or_404(el_posts, entid=entid)
    company_obj = ELPost.objects.filter(entid=entid).first()
    version = request.GET.get("version")  # 报告版本，10全景，11标准
    if version not in ["10", "11", ]:
        version = "10"
    part = request.GET.get("part")
    context = {"el_post": el_post, "version": version, }
    # 报告框架，封面综合评价
    if not part:
        # if customer_verify_fee(request, saas_pindao="20", saas_item=version, tkey=entid):
        # return HttpResponseRedirect(noauth_redirct_iframe)
        # 加载信用评分
        year_list = [2016, 2015, 2014, 2013]
        the_credit = {"total": [], "detail": []}
        context["latest_year"] = 2012
        for tyear in year_list:
            sr_obj = ELStatisticsCredit.objects.filter(year=tyear, region_name__isnull=False)
            sn_obj = ELStatisticsCredit.objects.filter(year=tyear, nic_name__isnull=False)
            credit_obj = ELCredit.objects.filter(entid_id=entid, year=tyear).first()
            if credit_obj:
                index_total = credit_obj.index_total if credit_obj.index_total else 360 + int(sum(
                    [credit_obj.index_3_1 * 0.05, credit_obj.index_3_2 * 0.05, credit_obj.index_3_3 * 0.05,
                     credit_obj.index_3_4 * 0.05,
                     credit_obj.index_3_5 * 0.05, credit_obj.index_3_6 * 0.05, credit_obj.index_3_7 * 0.05,
                     credit_obj.index_3_8 * 0.05,
                     credit_obj.index_3_9 * 0.12, credit_obj.index_3_10 * 0.12,
                     credit_obj.index_3_11 * 0.2, credit_obj.index_3_12 * 0.15]))
                # 增加电力分数
                credit_obj = add_power_score(credit_obj, company_obj.ENTNAME, tyear + 1)
                index_total = credit_obj.index_total
                the_credit["total"].append({"year": tyear + 1, "value": index_total})
                the_credit["detail"].append(
                    {"year": tyear + 1, "value": credit_obj, "statistic_r": sr_obj, "statistic_n": sn_obj})
                if (tyear + 1) > context["latest_year"]:
                    context["latest_year"] = tyear + 1
            else:
                tmp_obj = ELCredit()
                tmp_obj.entid_id = entid
                tmp_obj.year = tyear
                tmp_obj.index_2_1 = get_index_from_data_engine(21)
                tmp_obj.index_2_2 = get_index_from_data_engine(22)
                tmp_obj.index_2_3 = get_index_from_data_engine(23)
                tmp_obj.index_2_4 = get_index_from_data_engine(24)
                tmp_obj.index_2_5 = get_index_from_data_engine(25)
                tmp_obj.index_3_1 = get_index_from_data_engine(31)
                tmp_obj.index_3_2 = get_index_from_data_engine(32)
                tmp_obj.index_3_3 = get_index_from_data_engine(33)
                tmp_obj.index_3_4 = get_index_from_data_engine(34)
                tmp_obj.index_3_5 = get_index_from_data_engine(35)
                tmp_obj.index_3_6 = get_index_from_data_engine(36)
                tmp_obj.index_3_7 = get_index_from_data_engine(37)
                tmp_obj.index_3_8 = get_index_from_data_engine(38)
                tmp_obj.index_3_9 = get_index_from_data_engine(39)
                tmp_obj.index_3_10 = get_index_from_data_engine(310)
                tmp_obj.index_3_11 = get_index_from_data_engine(311)
                tmp_obj.index_3_12 = get_index_from_data_engine(312)
                tmp_obj.index_total = 360 + int(sum(
                    [tmp_obj.index_3_1 * 0.05, tmp_obj.index_3_2 * 0.05, tmp_obj.index_3_3 * 0.05,
                     tmp_obj.index_3_4 * 0.05,
                     tmp_obj.index_3_5 * 0.05, tmp_obj.index_3_6 * 0.05, tmp_obj.index_3_7 * 0.05,
                     tmp_obj.index_3_8 * 0.05,
                     tmp_obj.index_3_9 * 0.12, tmp_obj.index_3_10 * 0.12,
                     tmp_obj.index_3_11 * 0.2, tmp_obj.index_3_12 * 0.15]))  # 模拟电力模型分数
                tmp_obj.save()
                #  增加电力分数, 为tmp_obj 添加index_3_13
                tmp_obj = add_power_score(tmp_obj, company_obj.ENTNAME, tyear + 1)
                the_credit["total"].append({"year": tyear + 1, "value": tmp_obj.index_total})
                the_credit["detail"].append(
                    {"year": tyear + 1, "value": tmp_obj, "statistic_r": sr_obj, "statistic_n": sn_obj})
                if (tyear + 1) > context["latest_year"]:
                    context["latest_year"] = tyear + 1

        # 如果暂无该企业的任何评分，则展示默认数据
        if len(the_credit["total"]) == 0:
            sr_obj = ELStatisticsCredit.objects.filter(year=2014, region_name__isnull=False)
            sn_obj = ELStatisticsCredit.objects.filter(year=2014, nic_name__isnull=False)

            the_credit = {"total": [{"year": 2015, "value": tmp_obj.index_total}],
                          "detail": [{"year": 2015, "value": tmp_obj, "statistic_r": sr_obj, "statistic_n": sn_obj}]}
            context["latest_year"] = 2015
        context["credit"] = the_credit
        return render(request, "report/java_ui/company_report.html", context)

    # 工商基础
    elif part == "tab_gongshang":
        el_name_history = ELNameHistory.objects.filter(entid_id=entid).values_list("ENTNAME", flat=True)
        if len(el_name_history):
            context["el_name_history"] = ", ".join(el_name_history)
        context["el_managers"] = el_post.c_manager.all()
        context["el_invs"] = el_post.c_inv.all()
        context["el_modifys"] = el_post.c_modify.all().order_by("-ALTDATE")
        the_cancel = el_post.c_cancel.all().first()
        if the_cancel:
            context["el_cancel"] = the_cancel
        the_revoke = el_post.c_revoke.all().first()
        if the_revoke:
            context["el_revoke"] = the_revoke
        return render(request, "report/java_ui/company_report_basic.html", context)

    # 关联幕后
    elif part == "tab_related":
        # 企业对外投资
        context["el_entinvs"] = ELInv.objects.filter(entid_inv=entid)
        # 法人id
        fr_personid, other_personids = ELPost.get_person_ids(entid)
        # 法人对外投资和任职
        if fr_personid:
            context["el_frinvs"] = ELInv.objects.filter(personid=fr_personid).exclude(entobj=entid)
            context["el_frpositions"] = ELManager.objects.filter(personid=fr_personid).exclude(entobj=entid)
        # 股东高管对外投资和任职
        if len(other_personids) and version in ["10", ]:
            context["el_personinvs"] = ELInv.objects.filter(personid__in=other_personids).exclude(entobj=entid)
            context["el_personpositions"] = ELManager.objects.filter(personid__in=other_personids).exclude(entobj=entid)
        # 分支机构
        context["el_filiations"] = el_post.c_filiation.all()
        return render(request, "report/java_ui/company_report_related.html", context)

    # 财务分析的html
    elif part == "tab_caiwu" and version in ["10", ]:
        context['java_ui_entid'] = raw_entid;
        return render(request, "report/java_ui/company_report_caiwu.html", context)

    # 财务分析所需json
    elif part == "json_caiwu" and version in ["10", ]:
        caiwudata = {"finance": {}, "financeRate": {}, "customs": {"1": {}, "2": {}},
                     "goods": {2014: {}, 2015: {}, 2016: {}}}
        for year in [2012, 2013, 2014, 2015]:
            tax_year = ELFinanceTax.objects.filter(entid_id=entid, year=year).first()
            if tax_year:
                caiwudata["finance"][str(year)] = {"revenue": tax_year.revenue,
                                                   "sales_cost": tax_year.sales_cost if tax_year.sales_cost else "",
                                                   "sales_tax": tax_year.sales_tax if tax_year.sales_tax else "",
                                                   "sales_expense": tax_year.sales_expense if tax_year.sales_expense else "",
                                                   "G_expense": tax_year.G_expense if tax_year.G_expense else "",
                                                   "finance_expense": tax_year.finance_expense if tax_year.finance_expense else "",
                                                   "asset_devaluation_losses": tax_year.asset_devaluation_losses if tax_year.asset_devaluation_losses else "",
                                                   "fair_value_change": tax_year.fair_value_change if tax_year.fair_value_change else "",
                                                   "investment_income": tax_year.investment_income if tax_year.investment_income else "",
                                                   "operation_profit": tax_year.operation_profit if tax_year.operation_profit else "",
                                                   "non_operating_income": tax_year.non_operating_income if tax_year.non_operating_income else "",
                                                   "non_operating_expense": tax_year.non_operating_expense if tax_year.non_operating_expense else "",
                                                   "total_profit": tax_year.total_profit if tax_year.total_profit else "",
                                                   "assets_re": tax_year.assets_re if tax_year.assets_re else "",
                                                   "incometax_actual": tax_year.incometax_actual if tax_year.incometax_actual else "", }
            else:
                caiwudata["finance"][str(year)] = {"revenue": "", "sales_cost": "", "sales_tax": "",
                                                   "sales_expense": "", "G_expense": "",
                                                   "finance_expense": "", "asset_devaluation_losses": "",
                                                   "fair_value_change": "",
                                                   "investment_income": "", "operation_profit": "",
                                                   "non_operating_income": "",
                                                   "non_operating_expense": "", "total_profit": "", "assets_re": "",
                                                   "incometax_actual": "", }
            tax_index = ELFinanceIndex.objects.filter(entid_id=entid, year=year).first()
            if tax_index:
                caiwudata["financeRate"][str(year)] = {"gross": tax_index.gross if tax_index.gross else "",
                                                       "profit": tax_index.profit if tax_index.profit else "",
                                                       "profit_net": tax_index.profit_net if tax_index.profit_net else "",
                                                       "asset_return": tax_index.asset_return if tax_index.asset_return else "",
                                                       "income_increase": tax_index.income_increase if tax_index.income_increase else "",
                                                       "profit_increase": tax_index.profit_increase if tax_index.profit_increase else "",
                                                       "profit_net_increase": tax_index.profit_net_increase if tax_index.profit_net_increase else ""}
            else:
                caiwudata["financeRate"][str(year)] = {"gross": "", "profit": "", "profit_net": "", "asset_return": "",
                                                       "income_increase": "",
                                                       "profit_increase": "", "profit_net_increase": ""}
        # 海关企业月度详情
        hg_objs = ELHGEnt.objects.filter(entid_id=entid)
        if len(hg_objs):
            for tmonth in [1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1501, 1502, 1503,
                           1504, 1505, 1506, 1507, 1508,
                           1509, 1510, 1511, 1512, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608]:
                for tport in ["1", "2"]:
                    tax_hg = ELHGEntDetail.objects.filter(entid_id=entid, tmonth=tmonth, tport=tport).first()
                    if tax_hg:
                        caiwudata["customs"][tport][str(tmonth)] = tax_hg.scale if tax_hg.scale else ""
                    else:
                        caiwudata["customs"][tport][str(tmonth)] = ""
        else:
            caiwudata["customs"] = ""
        # 企业商品年度分类统计
        hg_goods = ELHGEntGoods.objects.filter(entid_id=entid)
        for hg_good in hg_goods:
            if hg_good.statics:
                goods_statics = json.loads(hg_good.statics)
                for key in goods_statics.keys():
                    good_name = ELHGGoodsCode.objects.filter(code=key).first()
                    if good_name:
                        goods_statics[good_name.name] = goods_statics[key]
                        del goods_statics[key]
                caiwudata["goods"][hg_good.tyear] = goods_statics
        return HttpResponse(json.dumps(caiwudata), content_type='application/json')

    # 风险失信
    elif part == "tab_fengxian":
        context["el_stockfrosts"] = ELStockFrost.objects.filter(entid_id=entid)
        context["el_stockimpawns"] = ELStockImpawn.objects.filter(entid_id=entid)
        context["el_liquidations"] = el_post.c_liquidation.all()
        context["case_basic"] = []
        case_basics = el_post.case_basic.all()
        for case in case_basics:
            the_detail = ELCaseDetail.objects.filter(caseid=case.caseid).first()
            if the_detail:
                case.CASETIME = the_detail.CASETIME
                case.CASEREASON = the_detail.CASEREASON
                case.CASEVAL = the_detail.CASEVAL
                case.EXESORT = the_detail.get_EXESORT_display()
                case.CASERESULT = the_detail.get_CASERESULT_display()
            the_punish = ELCasePunish.objects.filter(caseid=case.caseid).first()
            if the_punish:
                case.ILLEGACTTYPE = the_punish.ILLEGACTTYPE
                case.PENDECISSDATE = the_punish.PENDECISSDATE
                case.PENAUTH = the_punish.PENAUTH
                case.PENDECNO = the_punish.PENDECNO
                case.ILLEGFACT = the_punish.ILLEGFACT
                case.PENBASIS = the_punish.PENBASIS
                case.PENTYPE = the_punish.get_PENTYPE_display()
                case.PENRESULT = the_punish.get_PENRESULT_display()
                case.PENAM = the_punish.PENAM
                case.PENEXEST = the_punish.PENEXEST
            if the_detail or the_punish:
                context["case_basic"].append(case)
        return render(request, "report/java_ui/company_report_fengxian.html", context)

    # 资产交易
    elif part == "tab_jiaoyi" and version in ["10", ]:
        mort_objs = ELMortReg.objects.filter(entid_id=entid)
        if mort_objs.count():
            context["el_mort_guas"] = ELMortGua.objects.filter(MORREG_ID__in=[x.MORREG_ID for x in mort_objs])
        else:
            context["el_mort_guas"] = []
        for mort_obj in mort_objs:
            the_claim = mort_obj.mort_claim.all().first()
            if the_claim:
                mort_obj.the_claim = the_claim
            else:
                mort_obj.the_claim = ELMortClaim()
        context["el_morts"] = mort_objs
        context["el_patents"] = ELPatentEnt.objects.filter(entid_id=entid)
        # 土地信息
        context["land_objs"] = []
        # if el_post.REGNO != None and len(el_post.REGNO) > 7:
        #     land_dict = FBAPI(el_post.REGNO).get_land()
        #     if "total" in land_dict and "hits" in land_dict:
        #         context["land_total"] = land_dict["total"]
        #         land_objs = []
        #         key_dict = {"公告类别": "gglb", "公示期": "gsq", "出让年限": "crnx", "单位地址": "dwdz", "受让单位": "srdw",
        #                     "土地用途": "tdyt", "土地面积(公顷)": "tdmj",
        #                     "地块位置": "dkwz", "备注": "bz", "宗地编号": "zdbh", "成交价格(万元)": "cjjg", "标题": "title",
        #                     "电子邮件": "email", "联系人": "lxr",
        #                     "联系单位": "lxdw", "联系电话": "lxdh", "行政区": "qjx", "邮政编码": "postcode", }
        #         for tmp in land_dict["hits"]:
        #             new_obj = {"gglb": "", "gsq": "", "crnx": "", "dwdz": "", "srdw": "", "tdyt": "", "tdmj": "",
        #                        "dkwz": "", "bz": "",
        #                        "zdbh": "", "cjjg": "", "title": "", "email": "", "lxr": "", "lxdw": "", "lxdh": "",
        #                        "qjx": "", "postcode": "", }
        #             for key in key_dict.keys():
        #                 if key in tmp:
        #                     new_obj[key_dict[key]] = tmp[key]
        #             land_objs.append(new_obj)
        #         context["land_objs"] = land_objs



        # 软件著作权
        context["zzq_objs"] = ELCopyrightSoftware.objects.filter(entid=entid)  # FBAPI(el_post.REGNO).get_zzq()

        # 专利信息
        context["el_patents"] = ELPatentEnt.objects.filter(entid_id=entid)

        # 商标
        el_tminfo = ELTminfo.objects.filter(entid_id=entid)
        context["el_tminfo_count"] = el_tminfo.count()
        context["el_tminfo"] = el_tminfo[:200]

        # ICP备案
        # context["icp_objs"] = []
        # if el_post.REGNO is not None and len(el_post.REGNO) > 7:
        #     icp_dict = FBAPI(el_post.REGNO).get_icp()
        #     if "total" in icp_dict and "hits" in icp_dict:
        #         context["icp_total"] = icp_dict["total"]
        #         icp_objs = []
        #         key_dict = {"主办单位名称": "zbdw", "主办单位性质": "dwxz", "审核通过时间": "tgsj", "网站名称": "wzmc", "网站域名": "host",
        #                     "网站备案/许可证号": "bah", }
        #         for tmp in icp_dict["hits"]:
        #             if "网站域名" in tmp and isinstance(tmp["网站域名"], list):
        #                 tmp["网站域名"] = ";".join(tmp["网站域名"])
        #                 new_obj = {"zbdw": "", "dwxz": "", "tgsj": "", "wzmc": "", "host": "", "bah": "", }
        #                 for key in key_dict.keys():
        #                     if key in tmp:
        #                         new_obj[key_dict[key]] = tmp[key]
        #                 icp_objs.append(new_obj)
        #         context["icp_objs"] = icp_objs
        return render(request, "report/java_ui/company_report_jiaoyi.html", context)

    elif part == "tab_ele":
        try:
            data = getJsonData(company_obj.ENTNAME)
            if data is None or data == "":
                data = getJsonDetail()
        except TypeError as e:
            data = getJsonDetail()
        # data = getJsonDetail()
        context['data'] = data
        return render(request, "report/java_ui/company_report_electricity.html", context)

    # 事件舆情
    # elif part == "tab_news" and version in ["10", ]:
    #     context["news_objs"] = []
    #     if el_post.REGNO != None and len(el_post.REGNO) > 7:
    #         news_dict = FBAPI(el_post.REGNO).get_news()
    #         if "event" in news_dict and "total" in news_dict["event"] and "hits" in news_dict["event"]:
    #             news_dict = news_filter(news_dict)
    #             context["news_objs"] = news_dict["event"]["hits"]
    #     return render(request, "report/java_ui/company_report_news.html", context)

    # 招标招聘
    # elif part == "tab_zbzp" and version in ["10", ]:
    #     context["ztb_objs"] = []
    #     if el_post.REGNO != None and len(el_post.REGNO) > 7:
    #         ztb_dict = FBAPI(el_post.REGNO).get_bid()
    #         if "total" in ztb_dict and "hits" in ztb_dict:
    #             ztb_objs = []
    #             key_dict = {"发布时间": "fbsj", "公告类型": "gglx", "地区": "dq", "标题": "bt", "正文": "zw", "采购人": "cgr",
    #                         "采购品目": "cgpm", "代理机构": "dljg"}
    #             for tmp in ztb_dict["hits"]:
    #                 new_obj = {"fbsj": "", "gglx": "", "dq": "", "bt": "", "zw": "", "cgr": "", "cgpm": "", "dljg": ""}
    #                 for key in key_dict.keys():
    #                     if key in tmp:
    #                         new_obj[key_dict[key]] = tmp[key]
    #                         ztb_objs.append(new_obj)
    #             context["ztb_objs"] = ztb_objs
    #     zp_objs = WmyAPI(el_post.ENTNAME).get_zp()
    #     for tmp in zp_objs:
    #         for ky in ["job_name", "posttime", "location", "education_requirement", "experience_requirement",
    #                    "salary_range", "url"]:
    #             if ky not in tmp:
    #                 tmp[ky] = ""
    #     context["zp_objs"] = zp_objs
    #     return render(request, "report/java_ui/company_report_zbzp.html", context)
    return HttpResponse("")


@never_cache
def company_json_report_for_interface(request, entid):
    entid = wldecode(entid, addcrc=True)
    if not entid or entid > 500000000:
        raise Http404
    el_posts = ELPost.objects.all()
    el_post = get_object_or_404(el_posts, entid=entid)
    company_obj = ELPost.objects.filter(entid=entid).first()
    version = request.GET.get("version")  # 报告版本，10全景，11标准
    if version not in ["10", "11", ]:
        version = "10"
    part = request.GET.get("part")
    context = {"Post": {}, "Version": version, }
    context["Post"]["RegNo"] = el_post.REGNO
    context["Post"]["LegalRep"] = el_post.faren
    context["Post"]["RegCap"] = el_post.ent_basic.REGCAP
    context["Post"]["RegCapCur"] = el_post.ent_basic.REGCAPCUR
    # context["Post"]["EntStatus"] = el_post.ent_basic.ENTSTATUS
    context["Post"]["EntType"] = el_post.ent_basic.ENTTYPE
    context["Post"]["EsDate"] = el_post.ent_basic.ESDATE
    context["Post"]["OpFrom"] = el_post.ent_basic.OPFROM
    context["Post"]["OpTo"] = el_post.ent_basic.OPTO
    context["Post"]["RegionID"] = ""  # context["Post"]["RegionID"] = el_post.ent_class.region_id.fulltitle
    context["Post"]["Dom"] = el_post.ent_basic.DOM
    context["Post"]["RegOrg"] = el_post.ent_basic.REGORG
    context["Post"]["LocalAdm"] = el_post.ent_basic.LOCALADM
    if el_post.ent_basic.ORIREGNO or el_post.ent_basic.RECCAP:
        context["Post"]["OriRegNo"] = el_post.ent_basic.ORIREGNO
        context["Post"]["RecCap"] = el_post.ent_basic.RECCAP
    if el_post.ent_basic.EMPNUM or el_post.ent_basic.ENTPROPERTY:
        context["Post"]["EmpNum"] = el_post.ent_basic.EMPNUM
        # context["Post"]["EntProperty"] = el_post.ent_basic.ENTPROPERTY
    context["Post"]["Tel"] = el_post.ent_basic.TEL
    context["Post"]["ApprDate"] = el_post.ent_basic.APPRDATE
    context["Post"]["Emall"] = el_post.ent_basic.EMAIL
    context["Post"]["OpLoc"] = el_post.ent_basic.OPLOC
    if el_post.ent_basic.DOMPRORIGHT or el_post.ent_basic.INSFORM:
        context["Post"]["DomproPright"] = el_post.ent_basic.DOMPRORIGHT
        context["Post"]["InsForm"] = el_post.ent_basic.INSFORM
    if el_post.ent_basic.PARNUM or el_post.ent_basic.LIMPARNUM:
        context["Post"]["ParNum"] = el_post.ent_basic.PARNUM
        context["Post"]["LimParNum"] = el_post.ent_basic.LIMPARNUM
    if el_post.ent_basic.PARFORM or el_post.ent_basic.EXENUM:
        context["Post"]["Parform"] = el_post.ent_basic.PARFORM
        context["Post"]["ExeNum"] = el_post.ent_basic.EXENUM
    if el_post.ent_basic.ABUITEM:
        context["Post"]["AbuItem"] = el_post.ent_basic.ABUITEM
    if el_post.ent_basic.CBUITEM:
        context["Post"]["CbuItem"] = el_post.ent_basic.CBUITEM
    context["Post"]["OpsCope"] = el_post.ent_basic.OPSCOPE
    context["Post"]["NicID "] = ""  # context["Post"]["NicID "] = el_post.ent_class.nic_id.fulltitle
    if hasattr(el_post.ent_class, "seic_id"):
        context["Post"]["SeicId"] = el_post.ent_class.seic_id.fulltitle

    # 报告框架，封面综合评价
    if part == 'TabOverallMerit':
        context.pop("Post")
        year_list = [2016, 2015, 2014, 2013]
        the_credit = {"Total": [], "Detail": []}
        context["latest_year"] = 2012
        for tyear in year_list:
            sr_obj = ELStatisticsCredit.objects.filter(year=tyear, region_name__isnull=False).values()
            sn_obj = ELStatisticsCredit.objects.filter(year=tyear, nic_name__isnull=False).values()
            credit_obj = ELCredit.objects.filter(entid_id=entid, year=tyear).first()
            if not credit_obj:
                tmp_obj = ELCredit()
                tmp_obj.entid_id = entid
                tmp_obj.year = tyear
                tmp_obj.index_2_1 = get_index_from_data_engine(21)
                tmp_obj.index_2_2 = get_index_from_data_engine(22)
                tmp_obj.index_2_3 = get_index_from_data_engine(23)
                tmp_obj.index_2_4 = get_index_from_data_engine(24)
                tmp_obj.index_2_5 = get_index_from_data_engine(25)
                tmp_obj.index_3_1 = get_index_from_data_engine(31)
                tmp_obj.index_3_2 = get_index_from_data_engine(32)
                tmp_obj.index_3_3 = get_index_from_data_engine(33)
                tmp_obj.index_3_4 = get_index_from_data_engine(34)
                tmp_obj.index_3_5 = get_index_from_data_engine(35)
                tmp_obj.index_3_6 = get_index_from_data_engine(36)
                tmp_obj.index_3_7 = get_index_from_data_engine(37)
                tmp_obj.index_3_8 = get_index_from_data_engine(38)
                tmp_obj.index_3_9 = get_index_from_data_engine(39)
                tmp_obj.index_3_10 = get_index_from_data_engine(310)
                tmp_obj.index_3_11 = get_index_from_data_engine(311)
                tmp_obj.index_3_12 = get_index_from_data_engine(312)
                tmp_obj.index_total = 360 + int(sum(
                    [tmp_obj.index_3_1 * 0.05, tmp_obj.index_3_2 * 0.05, tmp_obj.index_3_3 * 0.05,
                     tmp_obj.index_3_4 * 0.05,
                     tmp_obj.index_3_5 * 0.05, tmp_obj.index_3_6 * 0.05, tmp_obj.index_3_7 * 0.05,
                     tmp_obj.index_3_8 * 0.05,
                     tmp_obj.index_3_9 * 0.12, tmp_obj.index_3_10 * 0.12,
                     tmp_obj.index_3_11 * 0.2, tmp_obj.index_3_12 * 0.15]))
                tmp_obj.save()

            credit_obj = ELCredit.objects.filter(entid_id=entid, year=tyear).first()
            if credit_obj:
                credit_obj = add_power_score(credit_obj, company_obj.ENTNAME, tyear + 1)
                score = {}
                score["BusPerformance"] = credit_obj.index_2_1
                score["OperStability"] = credit_obj.index_2_2
                score["DevAbility"] = credit_obj.index_2_3
                score["SocCapital"] = credit_obj.index_2_4
                score["ManTeam"] = credit_obj.index_2_5

                performance = {}
                performance["ProAbility"] = credit_obj.index_3_4
                performance["OperCost"] = credit_obj.index_3_5
                performance["FinaPressure"] = credit_obj.index_3_6
                performance["AssTurnoverCapacity"] = credit_obj.index_3_7
                performance["MarkPosition"] = credit_obj.index_3_8

                stability = {}
                stability["PowerStability"] = credit_obj.index_3_10
                stability["BusFluctuation"] = credit_obj.index_3_9
                stability["NegaRecord"] = 80
                stability["GroupStability"] = 75
                stability["Electricity"] = credit_obj.index_3_13

                ability = {}
                ability["FinaGrowth"] = credit_obj.index_3_11
                ability["RDInvestment"] = credit_obj.index_3_10
                ability["BusGrowth"] = credit_obj.index_3_10

                relations = {}
                relations["ShaChara"] = credit_obj.index_3_12
                relations["ShaAssociation"] = credit_obj.index_3_3
                relations["AssEntScore"] = 0

                team = {}
                team["TeamEduBackground"] = credit_obj.index_3_1
                team["IndExperience"] = credit_obj.index_3_2
                team["TeamManagementAbility"] = credit_obj.index_3_3

                index_total = credit_obj.index_total if credit_obj.index_total else int(sum(
                    [credit_obj.index_3_1 * 0.05, credit_obj.index_3_2 * 0.05, credit_obj.index_3_3 * 0.05,
                     credit_obj.index_3_4 * 0.05,
                     credit_obj.index_3_5 * 0.05, credit_obj.index_3_6 * 0.05, credit_obj.index_3_7 * 0.05,
                     credit_obj.index_3_8 * 0.05,
                     credit_obj.index_3_9 * 0.12, credit_obj.index_3_10 * 0.12,
                     credit_obj.index_3_11 * 0.2, credit_obj.index_3_12 * 0.15]))
                credit_obj = add_power_score(credit_obj, company_obj.ENTNAME, tyear + 1)
                index_total = credit_obj.index_total
                # index_total = int(math.sqrt(index_total * 10) * 10)
                # if index_total > 733:
                #     index_total = int(index_total * 0.9)
                the_credit["Total"].append({"Year": tyear + 1, "Value": index_total})
                the_credit["Detail"].append(
                    {"Year": tyear + 1, "Score": score, "Performance": performance, "Stability": stability,
                     "Ability": ability, "Relations": relations, "Team": team, "RegionTrend": list(sr_obj),
                     "IndustryTrend": list(sn_obj)})
                if (tyear + 1) > context["latest_year"]:
                    context["latest_year"] = tyear + 1
        # 如果暂无该企业的任何评分，则展示默认数据
        if len(the_credit["Total"]) == 0:
            sr_obj = ELStatisticsCredit.objects.filter(year=2014, region_name__isnull=False).values()
            sn_obj = ELStatisticsCredit.objects.filter(year=2014, nic_name__isnull=False).values()

            score = {}
            score["BusPerformance"] = 60
            score["OperStability"] = 60
            score["DevAbility"] = 60
            score["SocCapital"] = 60
            score["ManTeam"] = 60

            performance = {}
            performance["ProAbility"] = 60
            performance["OperCost"] = 60
            performance["FinaPressure"] = 60
            performance["AssTurnoverCapacity"] = 60
            performance["MarkPosition"] = 60

            stability = {}
            stability["PowerStability"] = 60
            stability["BusFluctuation"] = 60
            stability["NegaRecord"] = 60
            stability["GroupStability"] = 60
            stability["Electricity"] = 60

            ability = {}
            ability["FinaGrowth"] = 60
            ability["RDInvestment"] = 60
            ability["BusGrowth"] = 60

            relations = {}
            relations["ShaChara"] = 60
            relations["ShaAssociation"] = 60
            relations["AssEntScore"] = 60

            team = {}
            team["TeamEduBackground"] = 60
            team["IndExperience"] = 60
            team["TeamManagementAbility"] = 60

            the_credit = {"Total": [{"Year": 2015, "Value": 450}],
                          "Detail": [{"Year": 2015, "Score": score, "Performance": performance, "Stability": stability,
                                      "Ability": ability, "Relations": relations, "Team": team,
                                      "RegionTrend": list(sr_obj), "IndustryTrend": list(sn_obj)}]}
            context["latest_year"] = 2015
        context["TabOverallMerit"] = the_credit
        return HttpResponse(json.dumps(context, cls=MyEncoder), content_type='application/json')


    # 工商基础
    elif part == "TabBusinessBase":
        el_name_history = ELNameHistory.objects.filter(entid_id=entid).values_list("ENTNAME", flat=True)
        if len(el_name_history):
            context["Post"]["NameHistory"] = ", ".join(el_name_history)

        context["Managers"] = []
        for manager in el_post.c_manager.all():
            obj = {}
            obj["Name"] = manager.NAME
            # obj["Position"] = manager.POSITION
            # obj["Sex"] = manager.SEX
            obj["Birthday"] = manager.birthday
            obj["OffhFrom"] = manager.OFFHFROM
            obj["OffhTo"] = manager.OFFHTO
            context["Managers"].append(obj)

        context["Invs"] = []
        for inv in el_post.c_inv.all():
            obj = {}
            obj["SubcoNam"] = inv.SUBCONAM
            # obj["Inv"] = inv.INV
            obj["AccoNam"] = inv.ACCONAM
            obj["Currency"] = inv.CURRENCY
            obj["ConProp"] = inv.CONPROP
            obj["ConDate"] = inv.CONDATE
            # obj["ConForm"] = inv.CONFORM
            context["Invs"].append(obj)

        context["Modifys"] = []
        el_modify = el_post.c_modify.all().order_by("-ALTDATE")
        for modify in el_modify:
            obj = {}
            obj["AltDate"] = modify.ALTDATE
            # obj["AltItem"] = modify.ALTITEM
            obj["AltBe"] = modify.ALTBE
            obj["AltAf"] = modify.ALTAF
            context["Modifys"].append(obj)

        the_cancel = el_post.c_cancel.all().first()
        if the_cancel:
            context["Cancel"] = {}
            context["Cancel"]["CanDate"] = the_cancel.CANDATE
            # context["Cancel"]["CanRea"] = the_cancel.CANREA
            context["Cancel"]["CanAuth"] = the_cancel.CANAUTH

        the_revoke = el_post.c_revoke.all().first()
        if the_revoke:
            context["Revoke"] = {}
            context["Revoke"]["RevDate"] = the_revoke.REVDATE
            context["Revoke"]["IllegAct"] = the_revoke.ILLEGACT
            context["Revoke"]["RevBasis"] = the_revoke.REVBASIS

        return HttpResponse(json.dumps(context, cls=MyEncoder), content_type="application/json")

        # 关联幕后
    elif part == "TabBehindTheScenes":
        # 企业对外投资
        context.pop("Post")
        try:
            entinvs = ELInv.objects.filter(entid_inv=entid)
            list_ = list(entinvs.values())
            context["Entinvs"] = []
            for entinv, listItem in zip(entinvs, list_):
                obj = {}
                obj["SubConAm"] = entinv.SUBCONAM if listItem.get('SUBCONAM', -1) != -1 else None
                obj["Currency"] = entinv.CURRENCY if listItem.get('CURRENCY', -1) != -1 else None
                obj["ConProp"] = entinv.CONPROP if listItem.get('CONPROP', -1) != -1 else None
                obj["ConDate"] = entinv.CONDATE if listItem.get('CONDATE', -1) != -1 else None
                obj["EnthName"] = entinv.entid.ENTNAME
                # obj["GetReportUrl"] = entinv.entid.get_report_url
                context["Entinvs"].append(obj)

            # 法人id
            fr_personid, other_personids = ELPost.get_person_ids(entid)
            # 法人对外投资和任职
            if fr_personid:
                el_frinvs = list(ELInv.objects.filter(personid=fr_personid).exclude(entobj=entid).values())
                context["Frinvs"] = []
                for frinv in el_frinvs:
                    obj = {}
                    obj["Inv"] = frinv.INV
                    obj["EntName"] = frinv.entid.ENTNAME
                    obj["SubCoNam"] = frinv.get('SUBCONAM', None)
                    obj["Currency"] = frinv.CURRENCY
                    obj["ConProp"] = frinv.CONPROP
                    obj["ConDate"] = frinv.CONDATE
                    obj["GetReportUrl"] = frinv.entid.get_report_url
                    context["Frinvs"].append(obj)

                el_frpositions = ELManager.objects.filter(personid=fr_personid).exclude(entobj=entid)
                context["FrPosition"] = []
                for frposition in el_frpositions:
                    obj = {}
                    obj["Name"] = frposition.NAME
                    obj["EnthName"] = frposition.entid.ENTNAME
                    # obj["GetReportUrl"] = frposition.entid.get_report_url
                    obj["Position"] = frposition.POSITION
                    obj["Lerepsign"] = frposition.LEREPSIGN
                    obj["OffhFrom"] = frposition.OFFHFROM
                    obj["OffhTo"] = frposition.OFFHTO
                    context["FrPosition"].append(obj)

                    # 股东高管对外投资和任职
                    # if len(other_personids) and version in ["10", ]:
                    #     el_personinvs = list(ELInv.objects.filter(personid__in=other_personids).exclude(entobj=entid).values())
                    #     context["PersonInvs"] = el_personinvs
                    # if el_personinvs:
                    #     for personinv in el_personinvs:
                    #         obj = {}
                    #         obj["Inv"] = personinv.INV
                    #         obj["EntName"] = personinv.entid.ENTNAME
                    #         obj["SubCoNam"] = personinv.SUBCONAM
                    #         obj["Currency"] = personinv.CURRENCY
                    #         obj["ConProp"] = personinv.CONPROP
                    #         obj["ConDate"] = personinv.CONDATE
                    #         # obj["GetReportUrl"] = personinv.entid.get_report_url
                    #         context["PersonInvs"].append(obj)

                    # el_personpositions = ELManager.objects.filter(personid__in=other_personids).exclude(entobj=entid)
                    # context["PersonPositions"] = []
                    # for personposition in el_personpositions:
                    #     obj = {}
                    #     obj["Name"] = personposition.NAME
                    #     obj["EnthName"] = personposition.entid.ENTNAME
                    #     # obj["GetReportUrl"] = personposition.entid.get_report_url
                    #     # obj["Position"] = personposition.POSITION
                    #     obj["Lerepsign"] = personposition.LEREPSIGN
                    #     obj["OffhFrom"] = personposition.OFFHFROM
                    #     obj["OffhTo"] = personposition.OFFHTO
                    #     context["PersonPositions"].append(obj)

            # 分支机构
            el_filiations = el_post.c_filiation.all()
            context["Filiations"] = []
            for filiation in el_filiations:
                obj = {}
                obj["BrName"] = filiation.BRNAME
                obj["BrRegNo"] = filiation.BRREGNO
                obj["BrPrincipal"] = filiation.BRPRINCIPAL
                obj["BrAddr"] = filiation.BRADDR
                context["Filiations"].append(obj)
        except Exception, e:
            return HttpResponse(json.dumps({"err": str(e)}), content_type="application/json")
        return HttpResponse(json.dumps(context, cls=MyEncoder), content_type="application/json")
    # 财务分析所需json
    elif part == "JsonFinancialAnalysis" and version in ["10", ]:
        caiwudata = {"Finance": {}, "FinanceRate": {}, "Customs": {"1": {}, "2": {}},
                     "Goods": {2014: {}, 2015: {}, 2016: {}}}
        for year in [2012, 2013, 2014, 2015]:
            tax_year = ELFinanceTax.objects.filter(entid_id=entid, year=year).first()
            if tax_year:
                caiwudata["Finance"][str(year)] = {"Revenue": tax_year.revenue,
                                                   "SalesCost": tax_year.sales_cost if tax_year.sales_cost else "",
                                                   "SalesTax": tax_year.sales_tax if tax_year.sales_tax else "",
                                                   "SalesExpense": tax_year.sales_expense if tax_year.sales_expense else "",
                                                   "GExpense": tax_year.G_expense if tax_year.G_expense else "",
                                                   "FinanceExpense": tax_year.finance_expense if tax_year.finance_expense else "",
                                                   "AssetDevaluationLosses": tax_year.asset_devaluation_losses if tax_year.asset_devaluation_losses else "",
                                                   "FairValueChange": tax_year.fair_value_change if tax_year.fair_value_change else "",
                                                   "InvestmentIncome": tax_year.investment_income if tax_year.investment_income else "",
                                                   "OperationProfit": tax_year.operation_profit if tax_year.operation_profit else "",
                                                   "NonOperatingIncome": tax_year.non_operating_income if tax_year.non_operating_income else "",
                                                   "NonOperatingExpense": tax_year.non_operating_expense if tax_year.non_operating_expense else "",
                                                   "TotalProfit": tax_year.total_profit if tax_year.total_profit else "",
                                                   "AssetsRe": tax_year.assets_re if tax_year.assets_re else "",
                                                   "IncometaxActual": tax_year.incometax_actual if tax_year.incometax_actual else "", }
            else:
                caiwudata["Finance"][str(year)] = {"Revenue": "", "SlesCost": "", "SalesTax": "",
                                                   "SalesExpense": "", "GExpense": "",
                                                   "FinanceExpense": "", "AssetDevaluationLosses": "",
                                                   "FairValueChange": "",
                                                   "InvestmentIncome": "", "OperationProfit": "",
                                                   "NonOperatingIncome": "",
                                                   "NonOperatingExpense": "", "TotalProfit": "", "AssetsRe": "",
                                                   "IncometaxActual": "", }
            tax_index = ELFinanceIndex.objects.filter(entid_id=entid, year=year).first()
            if tax_index:
                caiwudata["FinanceRate"][str(year)] = {"Gross": tax_index.gross if tax_index.gross else "",
                                                       "Profit": tax_index.profit if tax_index.profit else "",
                                                       "ProfitNet": tax_index.profit_net if tax_index.profit_net else "",
                                                       "AssetReturn": tax_index.asset_return if tax_index.asset_return else "",
                                                       "IncomeIncrease": tax_index.income_increase if tax_index.income_increase else "",
                                                       "ProfitIncrease": tax_index.profit_increase if tax_index.profit_increase else "",
                                                       "ProfitNetIncrease": tax_index.profit_net_increase if tax_index.profit_net_increase else ""}
            else:
                caiwudata["FinanceRate"][str(year)] = {"Gross": "", "Profit": "", "ProfitNet": "", "AssetReturn": "",
                                                       "IncomeIncrease": "",
                                                       "ProfitIncrease": "", "ProfitNetIncrease": ""}
        # 海关企业月度详情
        hg_objs = ELHGEnt.objects.filter(entid_id=entid)
        if len(hg_objs):
            for tmonth in [1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1501, 1502, 1503,
                           1504, 1505, 1506, 1507, 1508,
                           1509, 1510, 1511, 1512, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608]:
                for tport in ["1", "2"]:
                    tax_hg = ELHGEntDetail.objects.filter(entid_id=entid, tmonth=tmonth, tport=tport).first()
                    if tax_hg:
                        caiwudata["Customs"][tport][str(tmonth)] = tax_hg.scale if tax_hg.scale else ""
                    else:
                        caiwudata["Customs"][tport][str(tmonth)] = ""
        else:
            caiwudata["Customs"] = ""
        # 企业商品年度分类统计
        hg_goods = ELHGEntGoods.objects.filter(entid_id=entid)
        for hg_good in hg_goods:
            if hg_good.statics:
                goods_statics = json.loads(hg_good.statics)
                for key in goods_statics.keys():
                    good_name = ELHGGoodsCode.objects.filter(code=key).first()
                    if good_name:
                        goods_statics[good_name.name] = goods_statics[key]
                        del goods_statics[key]
                caiwudata["Goods"][hg_good.tyear] = goods_statics
        return HttpResponse(json.dumps(caiwudata), content_type='application/json')
    # 风险失信
    elif part == "TabRiskDishonesty":
        context.pop("Post")
        el_stockfrosts = ELStockFrost.objects.filter(entid_id=entid)
        context["StockFrosts"] = []
        for stockfrost in el_stockfrosts:
            obj = {}
            obj["FrNum"] = stockfrost.FRODOCNO
            obj["FrOrgan"] = stockfrost.FROAUTH
            obj["FroFrom"] = stockfrost.FROFROM
            obj["FroTo"] = stockfrost.FROTO
            obj["FroAm"] = stockfrost.FROAM
            obj["ThawAuth"] = stockfrost.THAWAUTH
            obj["ThawDocNO"] = stockfrost.THAWDOCNO
            obj["ThawDate"] = stockfrost.THAWDATE
            obj["ThawComment"] = stockfrost.THAWCOMMENT
            context["StockFrosts"].append(obj)

        el_stockimpawns = ELStockImpawn.objects.filter(entid_id=entid)
        context["StockImpawns"] = []
        for stockimpawn in el_stockimpawns:
            obj = {}
            obj["ImpOrg"] = stockimpawn.IMPORG
            # obj["ImpOrgType"] = stockimpawn.IMPORGTYPE
            obj["ImpAm"] = stockimpawn.IMPAM
            obj["ImpOnrecDate"] = stockimpawn.IMPONRECDATE
            obj["ImpExaeep"] = stockimpawn.IMPEXAEEP
            obj["ImpSanDate"] = stockimpawn.IMPSANDATE
            obj["ImpTo"] = stockimpawn.IMPSANDATE
            context["StockImpawns"].append(obj)

        el_liquidations = el_post.c_liquidation.all()
        context["LiquidAtions"] = []
        for liquidation in el_liquidations:
            obj = {}
            obj["LiqRespon"] = liquidation.LIGENTITY
            obj["LiqOfficer"] = liquidation.LIGPRINCIPAL
            obj["LiqGropMem"] = liquidation.LIQMEN
            obj["LiqEnd"] = liquidation.LIGST
            obj["LiqEndDate"] = liquidation.LIGENDDATE
            obj["DebtUndertake"] = liquidation.DEBTTRANEE
            obj["BondUndertake"] = liquidation.CLAIMTRANEE
            obj["Tel"] = liquidation.TEL
            context["LiquidAtions"].append(obj)

        context["CaseBasic"] = []
        case_basics = el_post.case_basic.all()
        for case in case_basics:
            obj = {}
            the_detail = ELCaseDetail.objects.filter(caseid=case.caseid).first()
            if the_detail:
                obj["CaseTime"] = the_detail.CASETIME
                obj["CaseReason"] = the_detail.CASEREASON
                obj["CaseVal"] = the_detail.CASEVAL
                # obj["ExeClass"] = the_detail.get_EXESORT_display()
                # obj["CaseResult"] = the_detail.get_CASERESULT_display()
                # case.CASETIME = the_detail.CASETIME
                # case.CASEREASON = the_detail.CASEREASON
                # case.CASEVAL = the_detail.CASEVAL
                # case.EXESORT = the_detail.get_EXESORT_display()
                # case.CASERESULT = the_detail.get_CASERESULT_display()
            the_punish = ELCasePunish.objects.filter(caseid=case.caseid).first()
            if the_punish:
                obj["IllegactType"] = the_punish.ILLEGACTTYPE
                obj["PendecIssDate"] = the_punish.PENDECISSDATE
                obj["PenAuth"] = the_punish.PENAUTH
                obj["PendecNo"] = the_punish.PENDECNO
                obj["IllegFact"] = the_punish.ILLEGFACT
                obj["PenBasis"] = the_punish.PENBASIS
                # obj["PenaltyType"] = the_punish.get_PENTYPE_display()
                # obj["PenResult"] = the_punish.get_PENRESULT_display()
                obj["PenaltyAmount"] = the_punish.PENAM
                obj["PenExiest"] = the_punish.PENEXEST
            if the_detail or the_punish:
                context["CaseBasic"].append(obj)
        return HttpResponse(json.dumps(context, cls=MyEncoder), content_type="application/json")
        # return render(request, "report/includes/company_report_fengxian.html", context)

    # 资产交易
    elif part == "TabAssetTransaction" and version in ["10", ]:
        context.pop("Post")
        mort_objs = ELMortReg.objects.filter(entid_id=entid)
        if mort_objs.count():
            el_mort_guas = ELMortGua.objects.filter(MORREG_ID__in=[x.MORREG_ID for x in mort_objs])
            context["MortGuas"]["GuaName"] = el_mort_guas.GUANAME
            context["MortGuas"]["Own"] = el_mort_guas.OWN
            context["MortGuas"]["Guades"] = el_mort_guas.GUADES
        else:
            context["MortGuas"] = []
        context["Morts"] = []
        for mort_obj in mort_objs:
            obj = {}
            obj["CanDate"] = mort_obj.CANDATE
            obj["RegNo"] = mort_obj.MORREGCNO
            obj["MortgageOwner"] = mort_obj.MORTGAGOR
            obj["RegAuth"] = mort_obj.REGORG
            obj["RegDate"] = mort_obj.REGIDATE
            obj["StateType"] = mort_obj.get_MORTYPE_display

            the_claim = mort_obj.mort_claim.all().first()
            if the_claim:
                obj["SecuredScope"] = the_claim.WARCOV
                obj["DebtSecurAmount"] = the_claim.PRICLASECAM
                obj["PefperFrom"] = the_claim.PEFPERFORM
                obj["PefperTo"] = the_claim.PEFPERTO
                # mort_obj.the_claim = the_claim
            else:
                obj["SecuredScope"] = ELMortClaim().WARCOV
                obj["DebtSecurAmount"] = ELMortClaim().PRICLASECAM
                obj["PefperFrom"] = ELMortClaim().PEFPERFORM
                obj["PefperTo"] = ELMortClaim().PEFPERTO
                # mort_obj.the_claim = ELMortClaim()
            context["Morts"].append(obj)

        # 专利信息
        el_patents = ELPatentEnt.objects.filter(entid_id=entid)
        context["Patents"] = []
        for patent in el_patents:
            obj = {}
            obj["PatentNo"] = patent.patentid.patentno
            obj["PatenName"] = patent.patentid.patname
            obj["AppliDate"] = patent.patentid.applicant_date_patent
            obj["Class"] = patent.patentid.get_patent_class_display
            obj["State"] = patent.patentid.get_patent_state_display
            obj["PatentAbstract"] = patent.patentid.patent_abstract
            context["Patents"].append(obj)

        # 著作权
        context["CopyrightObjs"] = []
        if len(el_post.REGNO) > 7:
            zzq_dict = FBAPI(el_post.REGNO).get_zzq()
            if "total" in zzq_dict and "hits" in zzq_dict:
                context["zzq_total"] = zzq_dict["total"]
                zzq_objs = []
                key_dict = {'作品名称': 'zpmc', '首次发表日期': 'fbrq', '著作权人': 'zzqr', '软件简称': 'rjjc', '版本号': 'bbh',
                            '登记日期': 'djrq', '分类号': 'flh',
                            '公告日期': 'ggrq', '登记号': 'djh', '公告类型': 'gglx', '软件全称': 'rjqc', }
                for tmp in zzq_dict["hits"]:
                    new_obj = {'zpmc': '', 'fbrq': '', 'zzqr': '', 'rjjc': '', 'bbh': '', 'djrq': '', 'flh': '',
                               'ggrq': '', 'djh': '', 'gglx': '',
                               'rjqc': '', }
                    for key in key_dict.keys():
                        if key in tmp:
                            new_obj[key_dict[key]] = tmp[key]
                    obj = {}
                    obj["WorkName"] = new_obj["zpmc"]
                    obj["FirstPubDate"] = new_obj["fbrq"]
                    obj["CopyrightOwner"] = new_obj["zzqr"]
                    obj["SoftwareShort"] = new_obj["rjjc"]
                    obj["VersionNo"] = new_obj["bbh"]
                    obj["RegDate"] = new_obj.get("djri", "")
                    obj["ClassNumber"] = new_obj["flh"]
                    obj["NoticeDate"] = new_obj["ggrq"]
                    obj["RegNo"] = new_obj["djh"]
                    obj["NoticeType"] = new_obj["gglx"]
                    obj["SoftwareName"] = new_obj["rjqc"]
                    zzq_objs.append(obj)
                context["CopyrightObjs"] = zzq_objs

        return HttpResponse(json.dumps(context, cls=MyEncoder), content_type='application/json')

    # 电力模型
    elif part == "TabElectricity":
        context.pop("Post")
        try:
            data = getJsonData(company_obj.ENTNAME)
            if data is None or data == "":
                data = getJsonDetail()
        except TypeError as e:
            data = getJsonDetail()
        # data = getJsonDetail()
        return HttpResponse(data, content_type='application/json')
